package cn.webrx;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;

/**
 * <p>功能描述: </p>
 *
 * @author webrx
 * @version 1.0
 * @date 2020-06-11 14:17
 */
public class Demo {
    public static void main(String[] args) {
        JdbcRealm jr = new JdbcRealm();

        DruidDataSource ds = new DruidDataSource();
        ds.setUrl("jdbc:mysql:/db?serverTimezone=PRC");
        ds.setUsername("root");
        ds.setPassword("");
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        jr.setDataSource(ds);

        HashedCredentialsMatcher hm = new HashedCredentialsMatcher("md5");
        hm.setHashIterations(10);
        jr.setCredentialsMatcher(hm);
        jr.setSaltIsBase64Encoded(false);
        jr.setSaltStyle(JdbcRealm.SaltStyle.COLUMN);
        jr.setAuthenticationQuery("select passwd,username from db_admin where username = ?");

        DefaultSecurityManager dsm = new DefaultSecurityManager(jr);
        SecurityUtils.setSecurityManager(dsm);

        Subject su = SecurityUtils.getSubject();

        String u = "aa";
        String p = "aa";
        UsernamePasswordToken token = new UsernamePasswordToken(u, p);
        try {
            su.login(token);
        } catch (UnknownAccountException uae) {
            System.out.println("账号不存在，请检查账号");
        } catch (IncorrectCredentialsException ice) {
            System.out.println("密码不正确");
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (su.isAuthenticated()) {
            System.out.println("认证成功，欢迎:" + su.getPrincipal());
        }


    }
}
